<template>
  <div class="master-detail-container">
    <el-card class="master-table">
      <template #header>
        <div class="card-header">
          <el-icon>
            <List/>
          </el-icon>
          <span>字典</span>
        </div>
      </template>

      <el-form :inline="true" :model="masterQuery" class="query-form">
        <el-form-item label="字典名称">
          <el-input v-model="masterSearch" placeholder="请输入字典名称" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQueryMaster">查询</el-button>
          <el-button @click="resetMasterQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="table-toolbar">
        <el-button type="primary" @click="handleAddMaster" v-permission="'admin'">
          <el-icon>
            <Plus/>
          </el-icon>
          添加字典
        </el-button>
      </div>

      <el-table
          :data="masterData"
          max-height="calc(100vh - 420px)"
          border
          highlight-current-row
          @row-click="handleSelectMaster"
          :current-row="currentMasterRow"
          v-loading="masterLoading"
      >
        <el-table-column prop="dicTypeId" label="ID" width="80"/>
        <el-table-column prop="dicTypeLabel" label="字典名称"/>
        <el-table-column prop="dicTypeCode" label="字典编码" width="160"/>
        <el-table-column prop="orderNum" label="排序" width="120"/>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button v-permission="['admin']" size="small" @click="handleEditMaster(row)">编辑</el-button>
            <el-button v-permission="['admin']" size="small" @click="refreshDic(row)">刷新缓存</el-button>
            <el-button v-permission="['admin']" size="small" type="danger" @click="handleDeleteMaster(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            v-model:current-page="masterQuery.current"
            v-model:page-size="masterQuery.size"
            :total="masterTotal"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleQueryMaster"
            @current-change="fetchTableMasterData"
        />
      </div>
    </el-card>

    <el-card class="detail-table">
      <template #header>
        <div class="card-header">
          <el-icon>
            <Document/>
          </el-icon>
          <span>字典项</span>
          <span v-if="currentMasterRow" class="selection-hint">
            当前字典: <el-tag type="success" effect="plain">{{ currentMasterRow.dicTypeLabel }}</el-tag>
          </span>
        </div>
      </template>

      <el-form :inline="true" :model="detailQuery" class="query-form">
        <el-form-item label="字典项名称">
          <el-input v-model="detailSearch" placeholder="请输入字典项名称" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              @click="handleQueryDetail"
              :disabled="!currentMasterRow"
          >
            查询
          </el-button>
          <el-button @click="resetDetailQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="table-toolbar">
        <el-button type="primary" @click="handleAddDetail" v-permission="'admin'" :disabled="!currentMasterRow">
          <el-icon>
            <Plus/>
          </el-icon>
          添加字典项
        </el-button>
        <el-button
            type="danger"
            :disabled="!selectedDetails.length"
            @click="handleBatchDeleteDetail"
            v-permission="'admin'"
        >
          <el-icon>
            <Delete/>
          </el-icon>
          删除字典项
        </el-button>
      </div>

      <el-table
          :data="detailData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChangeDetail"
          v-loading="detailLoading"
          :disabled="!currentMasterRow"
          max-height="calc(100vh - 420px)"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="dicDataId" label="ID" width="80"/>
        <el-table-column prop="dicDataLabel" label="字典项名称"/>
        <el-table-column prop="dicDataValue" label="字典值" width="180"/>
        <el-table-column prop="orderNum" label="排序" width="120"/>
        <el-table-column label="状态" width="120">
          <template #default="scope">
            <DictSelect
                :model-value="scope.row.enableStatus"
                dicTypeCode="enable_status"
                display-only
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button v-permission="['admin']" size="small" @click="handleEditDetail(row)">编辑</el-button>
            <el-button v-permission="['admin']" size="small" type="danger" @click="handleDeleteDetail(row)">
              删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>

      <!-- 子表分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="detailQuery.current"
            v-model:page-size="detailQuery.size"
            :total="detailTotal"
            :disabled="!currentMasterRow"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @current-change="fetchTableDetailData"
            @size-change="handleQueryDetail"
        />
      </div>
    </el-card>

    <EditTypeDialog ref="EditTypeRef" @submit="handleSubmitMaster"></EditTypeDialog>
    <EditDataDialog ref="EditDataRef" @submit="handleSubmitDetail"></EditDataDialog>

  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, watch} from 'vue'
import {List, Document, Delete, Plus} from '@element-plus/icons-vue'
import {dicApi, tableInfoApi} from '@/api/core'
import {PageQuery} from "@/types/api"
import {ElMessageBox, ElMessage} from 'element-plus'

import {DicData} from "@/views/dic/DicData"
import {DicType} from "@/views/dic/DicType"
import EditTypeDialog from './editType.vue'
import EditDataDialog from './editData.vue'
import EditData from "@/views/dic/editData.vue";
import DictSelect from "@/components/DictSelect.vue";

const EditTypeRef = ref<InstanceType<typeof EditTypeDialog>>()
const EditDataRef = ref<InstanceType<typeof EditDataDialog>>()

const masterSearch = ref('')
const detailSearch = ref('')

const masterQuery = ref<PageQuery>({
  code: 'dic_type',
  current: 1,
  size: 10,
  queryParams: [{
    paramName: "dicTypeLabel",
    relation: "like",
    paramValue: ""
  }],
  querySorts: [{
    paramName: "orderNum",
    order: "desc"
  }]
})

const detailQuery = ref<PageQuery>({
  code: 'dic_data',
  current: 1,
  size: 10,
  queryParams: [
    {paramName: "dicDataLabel", relation: "like", paramValue: ""},
    {paramName: "dicTypeCode", relation: "eq", paramValue: ""}
  ],
  querySorts: [{paramName: "orderNum", order: "desc"}]
})

const masterData = ref<DicType[]>([])
const detailData = ref<DicData[]>([])

const masterTotal = ref(0)
const detailTotal = ref(0)

const masterLoading = ref(false)
const detailLoading = ref(false)

const selectedDetails = ref<DicData[]>([])

const currentMasterRow = ref<DicType | null>(null)

// -------------------- 主表操作 --------------------

watch(masterSearch, (newVal) => {
  if (masterQuery.value.queryParams && masterQuery.value.queryParams[0]) {
    masterQuery.value.queryParams[0].paramValue = newVal
  }
})

const fetchTableMasterData = () => {
  masterLoading.value = true
  masterQuery.value.queryParams![0].paramValue = masterSearch.value
  tableInfoApi.page(masterQuery.value).then(res => {
    masterData.value = res.data.records
    masterTotal.value = res.data.total
  }).finally(() => masterLoading.value = false)
}

const handleQueryMaster = () => {
  masterQuery.value.current = 1
  fetchTableMasterData()
}

const resetMasterQuery = () => {
  masterSearch.value = ''
  masterQuery.value.size = 10
  handleQueryMaster()
}

// -------------------- 主表行选中 --------------------
const handleSelectMaster = (row: DicType) => {
  currentMasterRow.value = row
  detailQuery.value.current = 1
  fetchTableDetailData()
}

// -------------------- 子表操作 --------------------
watch(currentMasterRow, (newVal) => {
  if (detailQuery.value.queryParams && detailQuery.value.queryParams[1]) {
    detailQuery.value.queryParams[1].paramValue = newVal?.dicTypeCode
  }
})

watch(detailSearch, (newVal) => {
  if (detailQuery.value.queryParams && detailQuery.value.queryParams[0]) {
    detailQuery.value.queryParams[0].paramValue = newVal
  }
})

const fetchTableDetailData = () => {
  if (!currentMasterRow.value) return
  detailLoading.value = true
  tableInfoApi.page(detailQuery.value).then(res => {
    detailData.value = res.data.records
    detailTotal.value = res.data.total
  }).finally(() => detailLoading.value = false)
}

const handleQueryDetail = () => {
  detailQuery.value.current = 1
  fetchTableDetailData()
}

const resetDetailQuery = () => {
  detailSearch.value = ''
  detailQuery.value.size = 10
  fetchTableDetailData()
}

// -------------------- CRUD 操作示例 --------------------
const handleAddMaster = () => {
  EditTypeRef.value?.openDialog()
}

const handleEditMaster = (row: DicType) => {
  EditTypeRef.value?.openDialog(row)
}

const handleSubmitMaster = (row: DicType) => {
  tableInfoApi.saveOrUpdate("dic_type", row).then(res => {
    ElMessage.success("保存字典成功")
    handleQueryMaster()
  })
}

const refreshDic =(row: DicType) => {
  dicApi.refresh(row.dicTypeCode).then(res => {
    ElMessage.success("刷新缓存成功")
  })
}

const handleDeleteMaster = (row: DicType) => {
  ElMessageBox.confirm(`确定删除字典 ${row.dicTypeLabel} 吗？`, '删除确认',{
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    tableInfoApi.deleteById("dic_type", "" + row.dicTypeId).then(() => {
      ElMessage.success('删除成功')
      handleQueryMaster()
    })
  }).catch(() => {
    // 点击取消，不做操作
  })
}

const handleAddDetail = () => {
  EditDataRef.value?.openDialog(currentMasterRow.value!.dicTypeCode)
}

const handleEditDetail = (row: DicData) => {
  EditDataRef.value?.openDialog(currentMasterRow.value!.dicTypeCode, row)
}

const handleSubmitDetail = (row: DicData) => {
  tableInfoApi.saveOrUpdate("dic_data", row).then(res => {
    ElMessage.success("保存字典项成功")
    handleQueryDetail()
  })
}

const handleDeleteDetail = (row: DicData) => {
  ElMessageBox.confirm(`确定删除字典项 ${row.dicDataLabel} 吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    tableInfoApi.deleteById("dic_data", "" + row.dicDataId).then(() => {
      ElMessage.success('删除成功')
      handleQueryDetail()
    })
  }).catch(() => {
    // 点击取消，不做操作
  })
}

const handleBatchDeleteDetail = () => {
  if (selectedDetails.value.length === 0) return
  ElMessageBox.confirm(`确定删除选中的 ${selectedDetails.value.length} 条字典项吗？`, '批量删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = selectedDetails.value.map(item => item.dicDataId).join(',')
    tableInfoApi.deleteByIds("dic_data", ids).then(() => {
      ElMessage.success("批量删除字典成功")
      selectedDetails.value = []
      handleQueryDetail()
    })
  }).catch(() => {
    // 点击取消，不做操作
  })
}

// -------------------- 多选 --------------------
const handleSelectionChangeDetail = (rows: DicData[]) => {
  selectedDetails.value = rows
}

// -------------------- 初始化 --------------------
onMounted(() => {
  fetchTableMasterData()
})
</script>


<style scoped>
.master-detail-container {
  display: flex;
  gap: 16px;
  height: 100%;
}

.table-toolbar {
  margin-bottom: 16px;
}

.master-table {
  width: 45%;
  min-width: 500px;
}

.detail-table {
  flex: 1;
  min-width: 600px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.selection-hint {
  margin-left: 12px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.query-form {
  margin-bottom: 16px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

/* 增强选中行的视觉效果 */
:deep(.el-table__row.current-row) {
  background-color: var(--el-color-primary-light-9);
}
</style>